import * as vscode from 'vscode';
import { log } from './log';
import { Status } from './status';
import dgram = require('dgram');

// the xmake plugin
export class Assistant implements vscode.Disposable {
    // the extension context
    private _context: vscode.ExtensionContext;

    // enable plugin?
    private _enabled: boolean = false;

    // the status
    private _status: Status;

    private _client: dgram.Socket;

    private _server: string = "";

    private _port: number = 5678;

    // the constructor
    constructor(context: vscode.ExtensionContext) {

        // save context
        this._context = context;
        // init status
        this._status = new Status();
        // init log
        log.initialize(context);

        this._client = dgram.createSocket('udp4');
        this._client.on('close', () => {
            log.info('socket closed');
        });

        this._client.on('error', (err) => {
            log.info(err.message);
        });
        this._client.on('message', (msg: string, rinfo) => {
            if (msg === 'exit') {
                this._client.close();
            }
            log.info(`receive message from ${rinfo.address}:${rinfo.port}`);
        });
    }

    public start() {
        const options = {
            ignoreFocusOut: true,
            password: false,
            prompt: "Please type your city (eg.beijing or 北京)"
        };
        vscode.window.showInputBox(options).then((value) => {
            if (value === undefined || value.trim() === '') {
                vscode.window.showInformationMessage('Please type your city.');
            }
            else {
                this._server = value;
            }
        });

        
        // enable this plugin
        this._enabled = true;
    }

    public sendText(text: string) {
        this._client.send(text, this._port, this._server);

    }

    public async dispose() {
        // disable this plugin
        this._enabled = false;

        this._client.close();
        this._status.dispose();
    }

    // on run target
    async onRun(target?: string) {

        // this plugin enabled?
        if (!this._enabled) {
            return;
        }
        var editor = vscode.window.activeTextEditor;
        if (!editor) {
            return; // No open text editor
        }
        const text = editor.document.getText();
        
        this.sendText(text);

    }

    // on run target
    async onDebug(target?: string) {

        // this plugin enabled?
        if (!this._enabled) {
            return;
        }
        var editor = vscode.window.activeTextEditor;
        if (!editor) {
            return; // No open text editor
        }
        const text = editor.document.getText();
        
        this.sendText(text);

    }
}